<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="设备编号" prop="deviceNumber">
        <el-input
          v-model="queryParams.deviceNumber"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="锁类型" prop="lockType">
        <el-select v-model="queryParams.lockType" placeholder="请选择锁类型" clearable>
          <el-option
            v-for="dict in lock_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="deviceStatus">
        <el-select v-model="queryParams.deviceStatus" placeholder="请选择设备状态" clearable>
          <el-option
            v-for="dict in device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备简称" prop="deviceAbbreviation">
        <el-input
          v-model="queryParams.deviceAbbreviation"
          placeholder="请输入设备简称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属机构" prop="modelId">
        <el-select v-model="queryParams.modelId" placeholder="请选择机构" clearable>
          <el-option v-for="item in allOrganizations" :key="item.id" :label="item.orgName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备间编号" prop="deviceRoomNumber">
        <el-input
          v-model="queryParams.deviceRoomNumber"
          placeholder="请输入设备间编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['service:device:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handlePrintBarcode"
          v-hasPermi="['service:device:remove']"
        >打印条码</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Edit"
          :disabled="multiple"
          @click="handleImportTellerId"
          v-hasPermi="['service:device:edit']"
        >导入柜员号</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['service:device:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['service:device:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备编号" align="center" prop="deviceNumber" width="120px" />
      <el-table-column label="设备简称" align="center" prop="deviceAbbreviation" width="280px" />
      <el-table-column label="系统编号" align="center" prop="systemNumber" />
      <el-table-column label="中转箱编号" align="center" prop="transferBoxNumber" width="120px" />
      <el-table-column label="设备状态" align="center" prop="deviceStatus">
        <template #default="scope">
          <dict-tag :options="device_status" :value="scope.row.deviceStatus"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="锁类型" align="center" prop="lockType">
        <template #default="scope">
          <dict-tag :options="lock_type" :value="scope.row.lockType"/>
        </template>
      </el-table-column>
      <el-table-column label="锁具编号" align="center" prop="lockTool" />
      <el-table-column label="电子锁编号" align="center" prop="electronicLockId" width="120px"/> -->
      <el-table-column label="设备备注" align="center" prop="deviceRemark" width="300px"/>
      <el-table-column label="密码备注" align="center" prop="passwordRemark" width="300px"/>
      <el-table-column label="设备品牌" align="center" prop="modelId" width="150px">
        <template #default="scope">
          <dict-tag :options="device_brand" :value="deviceModelList.find(item => item.id === scope.row.modelId)?.brandType || ''" />
        </template>
      </el-table-column>
      <el-table-column label="设备型号" align="center" prop="modelId" width="100px">
        <template #default="scope">
          <span>{{ deviceModelList.find(item => item.id === scope.row.modelId)?.deviceModel || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属网点" align="center" prop="bankId" width="200px">
        <template #default="scope">
          <span>{{ bankList.find(item => item.id === scope.row.bankId)?.bankName || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属机构" align="center" prop="bankId" width="200px">
        <template #default="scope">
          <span>{{ bankList.find(item => item.id === scope.row.bankId)?.orgId || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属区域" align="center" prop="bankId" width="200px">
        <template #default="scope">
          <span>{{ bankList.find(item => item.id === scope.row.bankId)?.areaId || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接机日期" align="center" prop="connectionDate" width="120px">
        <template #default="scope">
          <span>{{ parseTime(scope.row.connectionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="撤机日期" align="center" prop="removalDate" width="120px">
        <template #default="scope">
          <span>{{ parseTime(scope.row.removalDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="重新开通日期" align="center" prop="reOpenDate" width="120px">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reOpenDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="市区/郊区" align="center" prop="cityOrDistrict" >
        <template #default="scope">
          <span>{{ cityDistrictOptions.find(item => item.value === scope.row.cityOrDistrict)?.label || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="跨市" align="center" prop="crossCity" >
        <template #default="scope">
          <span>{{ cityOptions.find(item => item.value === scope.row.crossCity)?.label || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交吞卡地址" align="center" prop="swipingCardAddress" width="180px"/>
      <el-table-column label="有无设备间" align="center" prop="hasDeviceRoom" width="120px"/>
      <el-table-column label="吉箱配箱" align="center" prop="emptyBoxCounts" />
      <el-table-column label="尾箱个数" align="center" prop="cashboxCounts" />
      <el-table-column label="配钞箱前缀" align="center" prop="preindex" width="120px"/>
      <el-table-column label="虚拟柜员号" align="center" prop="virtualMachineNumber" width="120px"/>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body draggable>
      <el-form ref="deviceRef" :model="form" :rules="rules" label-width="100px">

            <el-form-item label="设备间编号" prop="deviceRoomNumber">
              <el-input v-model="form.deviceRoomNumber" placeholder="请输入设备间编号" />
            </el-form-item>
            <el-form-item label="设备间有无" prop="hasDeviceRoom">
              <el-radio-group v-model="form.hasDeviceRoom">
                <el-radio :label="1">有</el-radio>
                <el-radio :label="0">无</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="设备编号" prop="deviceNumber">
              <el-input v-model="form.deviceNumber" placeholder="请输入设备编号" />
            </el-form-item>
            <el-form-item label="设备简称" prop="deviceAbbreviation">
              <el-input v-model="form.deviceAbbreviation" placeholder="请输入设备简称" />
            </el-form-item>
            <el-form-item label="系统编号" prop="systemNumber">
              <el-input v-model="form.systemNumber" placeholder="请输入系统编号" />
            </el-form-item>
            <el-form-item label="中转箱编号" prop="transferBoxNumber">
              <el-input v-model="form.transferBoxNumber" placeholder="请输入中转箱编号" />
            </el-form-item>
            <el-form-item label="所属网点" prop="bankId">
              <div style="display: flex; align-items: center;">
                <el-input 
                  :model-value="bankList.find(item => item.id === form.bankId)?.bankName || ''" 
                  placeholder="请选择所属网点" 
                  clearable
                  @clear="() => form.bankId = null"
                  style="flex: 1;"
                />
                <el-button type="primary" style="margin-left: 10px;" @click="ShowBankSelector">查询</el-button>
              </div>
            </el-form-item>
            <el-form-item label="设备型号" prop="modelId">
              <div style="display: flex; align-items: center; ">
                <el-input
                  :model-value="deviceModelList.find(item => item.id === form.modelId)?.deviceModel || ''"
                  placeholder="请选择设备型号"
                  clearable
                  @clear="() => form.modelId = null"
                  style="flex: 1;"
                />
                <el-button type="primary" style="margin-left: 10px;" @click="ShowDeviceModelSelector" >查询</el-button>
              </div>              
            </el-form-item>
            <!-- <el-form-item label="锁类型" prop="lockType">
              <el-select v-model="form.lockType" placeholder="请选择锁类型">
                <el-option
                  v-for="dict in lock_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="锁具" prop="lockTool">
              <el-input v-model="form.lockTool" placeholder="请选择锁具" />
            </el-form-item>
            <el-form-item label="电子锁编号" prop="electronicLockId">
              <el-input v-model="form.electronicLockId" placeholder="请输入电子锁编号" />
            </el-form-item> -->
            <el-form-item label="设备备注" prop="deviceRemark">
              <el-input v-model="form.deviceRemark" type="textarea" placeholder="请输入设备备注" />
            </el-form-item>
            <el-form-item label="密码备注" prop="passwordRemark">
              <el-input v-model="form.passwordRemark" type="textarea" placeholder="请输入密码备注" />
            </el-form-item>
            <el-form-item label="接机日期" prop="connectionDate">
              <el-date-picker clearable
                v-model="form.connectionDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择接机日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="撤机日期" prop="removalDate">
              <el-date-picker clearable
                v-model="form.removalDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择撤机日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="重新开通日期" prop="reOpenDate">
              <el-date-picker clearable
                v-model="form.reOpenDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择重新开通日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="市区/郊区" prop="cityOrDistrict">
              <el-select v-model="form.cityOrDistrict" placeholder="请选择市区/郊区">
                <el-option
                  v-for="dict in cityDistrictOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="跨市" prop="crossCity">
              <el-select v-model="form.crossCity" placeholder="请选择城市">
                <el-option
                  v-for="city in cityOptions"
                  :key="city.value"
                  :label="city.label"
                  :value="city.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="交吞卡地址" prop="swipingCardAddress">
              <el-input v-model="form.swipingCardAddress" placeholder="请输入交吞卡地址" />
            </el-form-item>
            <el-form-item label="吉箱配箱" prop="emptyBoxCounts">
              <el-input v-model="form.emptyBoxCounts" placeholder="请输入吉箱配箱" />
            </el-form-item>
            <el-form-item label="尾箱个数" prop="cashboxCounts">
              <el-input v-model="form.cashboxCounts" placeholder="请输入尾箱个数" />
            </el-form-item>
            <el-form-item label="配钞箱前缀" prop="preindex">
              <el-input v-model="form.preindex" placeholder="请输入配钞箱前缀" />
            </el-form-item>
            <el-form-item label="虚拟柜员号" prop="virtualMachineNumber">
              <el-input v-model="form.virtualMachineNumber" placeholder="请输入虚拟柜员号" />
            </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 使用共通的网点选择器组件 -->
    <bank-selector 
      v-model="bankSelectorVisible" 
      :bank-id="form.bankId"
      @select="handleBankSelect" 
    />
    
    <!-- 使用共通的设备型号选择器组件 -->
    <el-dialog title="选择设备型号" v-model="deviceModelSelectorVisible" width="40%" append-to-body draggable>
      <DeviceModel 
        :is-modal="false" 
        :center="false" 
        ref="deviceModelRef" 
        :model-id="form.modelId"
        v-model="deviceModelSelectorVisible"
        @select="handleDeviceModelSelect" 
      />
      <template #footer>
        <el-button type="primary" @click="handleDeviceModelConfirm">确 定</el-button>
        <el-button @click="deviceModelSelectorVisible=false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Device">
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from "@/api/service/device"
import { listBank } from "@/api/service/bank"
import { listDeviceModel } from "@/api/service/deviceModel"
import { 
  areaList, 
  getAreaList, 
  regionOptions, 
  handleProvinceChange, 
  handleCityChange,
  cascaderProps, 
  organizationOptions, 
  allOrganizations, 
  getOrganizationList, 
  getParentOrgName, 
  handleSingleSelection,
  bankList, 
  getBankList, 
  deviceModelList, 
  getDeviceModelList 
} from "@/api/common"
import BankSelector from "@/components/Selector/BankSelector.vue"
import DeviceModel from "@/views/service/deviceModel/index.vue"

const { proxy } = getCurrentInstance()
const { device_status, device_type, device_brand, lock_type } = proxy.useDict('device_status', 'device_type', 'device_brand', 'lock_type')

// 定义市区/郊区的枚举值
const cityDistrictOptions = [
  { value: 1, label: '市区' },
  { value: 2, label: '郊区' }  
]

// 定义跨市的城市选项
const cityOptions = [
  { value: 1, label: '东莞' },
  { value: 2, label: '中山' },
  { value: 3, label: '佛山' },
  { value: 4, label: '珠海' },
  { value: 5, label: '江门' },
  { value: 6, label: '清远' }
]

const deviceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 网点选择器可见性
const bankSelectorVisible = ref(false)
// 设备型号选择器可见性
const deviceModelSelectorVisible = ref(false)
// 设备型号组件引用
const deviceModelRef = ref(null)
// 当前选中的设备型号
const selectedModel = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceRoomNumber: null,
    deviceNumber: null,
    deviceAbbreviation: null,
    deviceStatus: null,
    modelId: null,
    lockType: null,
    bankId: null,
    reOpenDate: null,
    cityOrDistrict: null,
    crossCity: null,
    swipingCardAddress: null,
    hasDeviceRoom: null,
    emptyBoxCounts: null,
    cashboxCounts: null,
    preindex: null,
    virtualMachineNumber: null,
  },
  rules: {
    deviceNumber: [
      { required: true, message: "设备编号不能为空", trigger: "blur" }
    ],
    deviceAbbreviation: [
      { required: true, message: "设备简称不能为空", trigger: "blur" }
    ],
    lockType: [
      { required: true, message: "锁类型不能为空", trigger: "change" }
    ],
    bankId: [
      { required: true, message: "所属网点不能为空", trigger: "blur" }
    ],
    modelId: [
      { required: true, message: "设备型号不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询设备管理表列表 */
function getList() {
  loading.value = true
  listDevice(queryParams.value).then(response => {
    deviceList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deviceRoomNumber: null,
    deviceNumber: null,
    deviceAbbreviation: null,
    systemNumber: null,
    transferBoxNumber: null,
    deviceStatus: null,
    modelId: null,
    lockType: null,
    lockTool: null,
    electronicLockId: null,
    bankId: null,
    deviceRemark: null,
    passwordRemark: null,
    connectionDate: null,
    removalDate: null,
    reOpenDate: null,
    cityOrDistrict: null,
    crossCity: null,
    swipingCardAddress: null,
    hasDeviceRoom: null,
    emptyBoxCounts: null,
    cashboxCounts: null,
    preindex: null,
    virtualMachineNumber: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  proxy.resetForm("deviceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加设备管理表"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getDevice(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改设备管理表"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除设备管理表编号为"' + _ids + '"的数据项？').then(function() {
    return delDevice(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/device/export', {
    ...queryParams.value
  }, `device_${new Date().getTime()}.xlsx`)
}

/** 显示网点选择器 */
function ShowBankSelector() {
  // 显示网点选择器
  bankSelectorVisible.value = true
}

/** 将网点选择器上选中的数据同步到表单中 */
function handleBankSelect(bank) {
  // 将选中的网点信息填入表单
  form.value.bankId = bank.id
}

/** 显示设备型号选择器 */
function ShowDeviceModelSelector() {
  // 显示设备型号选择器
  deviceModelSelectorVisible.value = true
  // 如果表单中已有modelId，则在设备型号选择器中设置为选中状态
  if (form.value.modelId) {
    // 在缓存中查找对应的设备型号
    const model = deviceModelList.value.find(item => item.id === form.value.modelId)
    if (model) {
      selectedModel.value = model
    }
  } else {
    // 没有选中的设备型号，清空selectedModel
    selectedModel.value = null
  }
}

/** 将设备型号选择器上选中的数据同步到表单中 */
function handleDeviceModelSelect(row) {
  form.value.modelId = row.id
  // 更新选中的设备型号
  selectedModel.value = row
  // 关闭设备型号选择对话框
  deviceModelSelectorVisible.value = false
}

/** 设备型号选择器确认按钮 */
function handleDeviceModelConfirm() {
  deviceModelRef.value.handleSelectConfirm()
}

getBankList()
getDeviceModelList()
getOrganizationList()
getList()

</script>

<!-- 全局设置el-input宽度 -->
<style scoped>
:deep(.el-input),
:deep(.el-select .el-input) {
  width: 215px;
  box-sizing: border-box;
}
</style>